<?php

namespace app\admin\controller;

use app\admin\service\CommonService;
use app\models\DictionaryModel;
use app\models\MyApprovalModel;
use app\models\MyApprovalRelationModel;
use app\models\MyNoticeModel;
use app\models\MyNoticeObjectModel;
use app\models\ParentInformationModel;
use app\models\SettingModel;
use app\models\SystemConfigModel;
use app\models\UserModel;
use think\Console;
use think\Db;

class System extends Common
{
	/**
	 * 平台设置
	 * User: Truman
	 * Date: 2020/08/14
	 *
	 * @return array|mixed
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function setting()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$data = input('param.');
			foreach ($data as $k => $v) {
				$result = (new SettingModel())->setValue($k, $v);
				//如果出错，就返回，如果是没有此参数，就默认跳过
				if (!$result['status'] && 10008 !== $result['data']) {
					return $result;
				}
			}
			$result = [
				'status' => true,
				'data' => [],
				'msg' => '保存成功！ 页面即将自动刷新~',
			];
			//配置保存后，清理缓存
			\think\Cache::clear(); //TODO 如果开启其他缓存，记得这里要配置缓存配置信息
			Console::call('clear'); //清除缓存
			return $result;
		}

		$platform_settings = (new SettingModel())->getAll();

		return $this->fetch('', ['platform_settings' => $platform_settings]);
	}
    /**
     * 系统配置
     * User: wufeng
     * Date: 2020/03/22.
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function system()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $configs = (new SystemConfigModel())->where('group', 1)
                ->field('id,name,type')
                ->select();
            $configList = [];
            foreach ($configs as $config) {
                $configList[] = [
                    'id' => $config['id'],
                    'name' => $config['name'],
                    'value' => $data[$config['name']],
                ];
            }
            if (false !== (new SystemConfigModel())->saveAll($configList)) {
                $this->success('保存成功！ 页面即将自动跳转~', '', '', 1);
            } else {
                $this->success('保存失败！ 页面即将自动跳转~', '', '', 1);
            }
        }
        $group = (new SystemConfigModel())
            ->where(['group' => 1])
            ->select()
            ->toArray();

        return $this->fetch('', [
            'group' => $group,
        ]);
    }

    /**
     * 配置
     * User: wufeng
     * Date: 2020/03/23.
     *
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function config()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $campus = (new SystemConfigModel())->getConfigLists($param);
            $this->success('success', '', $campus, 0);
        }

        return $this->fetch();
    }

	/**
	 * User: wufeng
	 * Date: 2020/03/31
	 *
	 */
    public function check_status()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            if (1 === (int) $data['status']) {
                $msg = '启用';
            } else {
                $msg = '禁用';
            }

            $res = (new SystemConfigModel())->save($data, ['id' => $data['id']]);

            if (false !== $res) {
                $this->success($msg.'成功', '', '', 1);
            }
            $this->error($msg.'失败', null, '', 1);
        }
    }

    /**
     * 添加配置
     * User: wufeng
     * Date: 2020/03/22.
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function add_config()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $res = (new SystemConfigModel())->save(input('post.'));
            if (false !== $res) {
                $this->success('添加成功', '', '', 1);
            }
            $this->error('添加失败', null, '', 1);
        }
        $config_type_list = (new DictionaryModel())
            ->where(['type' => 33])
            ->select()
            ->toArray();
        $config_group_list = (new DictionaryModel())
            ->where(['type' => 34])
            ->select()
            ->toArray();

        return $this->fetch('', [
            'config_type_list' => $config_type_list,
            'config_group_list' => $config_group_list,
        ]);
    }

    /**
     * 编辑配置
     * User: wufeng
     * Date: 2020/03/22.
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function edit_config()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $_data = input('post.');
            $res = (new SystemConfigModel())->save($_data, ['id' => $_data['id']]);
            if (false !== $res) {
                $this->success('编辑成功', '', '', 1);
            }
            $this->error('添加失败', null, '', 1);
        }

        $config_type_list = (new DictionaryModel())
            ->where(['type' => 33])
            ->select()
            ->toArray();
        $config_group_list = (new DictionaryModel())
            ->where(['type' => 34])
            ->select()
            ->toArray();
        $systemConfig = (new SystemConfigModel())->get(input('id'));

        return $this->fetch('', [
            'systemConfig' => $systemConfig,
            'config_type_list' => $config_type_list,
            'config_group_list' => $config_group_list,
        ]);
    }

    /**
     * User: wufeng
     * Date: 2020/03/24.
     *
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function notice()
    {
        if ($this->request->isAjax()) {
            $params = $this->request->param();
            $myNoticeObject = (new MyNoticeObjectModel())->getMyNoticeObjectLists($params);
            $this->success('success', '', $myNoticeObject, 0);
        }

        return $this->fetch();
    }

    /**
     * User: wufeng
     * Date: 2020/03/24.
     *
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function notice_detail()
    {
        $myNoticeObject = (new MyNoticeObjectModel())->get(input('id'));
        $myNotice = (new MyNoticeModel())->get($myNoticeObject['notice_id']);
        (new MyNoticeObjectModel())->save(['is_read' => 1], ['id' => input('id')]);

        return $this->fetch('', [
            'myNotice' => $myNotice,
        ]);
    }

    /**
     * 审批列表
     * User: wufeng
     * Date: 2020/03/24.
     */
    public function approval()
    {
        if ($this->request->isAjax()) {
            $params = $this->request->param();
			$params['operation_type'] = 1;
            $approval = (new MyApprovalModel())->approvalLists($params);
            $this->success('success', '', $approval, 0);
        }

        return $this->fetch();
    }

    /**
     * User: wufeng
     * Date: 2020/03/26.
     *
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function approval_rejection()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $params = input('post.');
            if (4 === (int) $params['status']) {
                $res = (new MyApprovalModel())->save(['status' => $params['status']], ['id' => $params['id']]);
				$where['approver_id'] = get_current_id();
				$where['approval_id'] = $params['id'];
				$data['status'] = $params['status'];
				$data['approval_time'] = date('Y-m-d H:i:s');
				Db::name('edu_my_approval_relation')->where($where)->update($data);
                if (false !== $res) {
                    $this->success('撤销成功', '', '', 1);
                }
                $this->error('撤销失败', null, '', 1);
            } else {
                $where = $data = [];
                $approval = (new MyApprovalModel())->get($params['id']);
                $where['approver_id'] = get_current_id();
                $where['approval_id'] = $params['id'];
                $data['status'] = $params['status'];
                $data['approval_content'] = $params['approval_content'];
                $data['approval_time'] = date('Y-m-d H:i:s');
                Db::name('edu_my_approval_relation')->where($where)->update($data);
                $flag = 1;
                if (1 === $approval['type']) {  //同事
                    $flag = 2;
                } elseif (2 === $approval['type']) {  //学生
                    $flag = 1;
                }
                $check = Db::name('edu_my_approval_relation')->where(['approval_id' => $params['id'], 'status' => 3])->find();
                if ($check) {
                    Db::name('edu_my_approval')->where(['id' => $params['id']])->update(['status' => 3]);
                    CommonService::writeNotice($approval['user_id'], $approval['approval_name'], $approval['approval_name'].'审批'.'已被驳回', $flag, 2);
                }

                $my_approval = Db::name('edu_my_approval')->where(['id' => $params['id']])->find();
                $student_id = (new ParentInformationModel())->get($my_approval['user_id'])['student_id'];
                $my_approval_count = Db::name('edu_my_approval_relation')->where(['approval_id' => $params['id']])->count();
                $my_approval_status_count = Db::name('edu_my_approval_relation')->where(['approval_id' => $params['id'], 'status' => 2])->count();
                if ($my_approval_count === $my_approval_status_count) {
                    Db::name('edu_my_approval')->where(['id' => $params['id']])->update(['status' => 2]);
                    Db::name('edu_class_subject_student_infos')->where(['class_manage_details_id' => $my_approval['cmdl_id'], 'student_id' => $student_id])->update(['attendance_reasons' => $my_approval['approval_name'], 'remarks' => $my_approval['approval_content']]);
                    CommonService::writeNotice($approval['user_id'], $approval['approval_name'], $approval['approval_name'].'审批'.'已被通过', $flag, 2);
                }
                $this->success('操作成功', '', '', 1);
            }
        }

        $approval = (new MyApprovalModel())->get(input('id'));
        $approval['user_name'] = (new UserModel())->get($approval['user_id'])['name'];
        $approval_lists = (new MyApprovalRelationModel())
            ->where(['approval_id' => input('id')])
            ->select()
            ->toArray();
        foreach ($approval_lists as &$list) {
        	$user = (new UserModel())->get($list['approver_id']);
            $list['name'] = $user['name'];
            if(1 === (int) $user['img']){
				$list['img'] = '/img.jpg';
			}else{
				$list['img'] = $user['img'];
			}
            if (1 === (int) $list['status']) {
                $list['status_text'] = '<span style="color:#c4f2f9;font-weight: bold;">待审批</span>';
            } elseif (2 === (int) $list['status']) {
                $list['status_text'] = '<span style="color:#00B83F;font-weight: bold;">已审批</span>';
            } elseif (3 === (int) $list['status']) {
                $list['status_text'] = '<span style="color:#c54736;font-weight: bold;">已驳回</span>';
            } elseif (4 === (int) $list['status']) {
                $list['status_text'] = '<span style="color:#c09853;font-weight: bold;">已撤销</span>';
            }
        }

        return $this->fetch('', [
            'approval' => $approval,
            'approval_lists' => $approval_lists,
        ]);
    }

	/**
	 * 协同列表
	 * User: wufeng
	 * Date: 2020/04/06
	 *
	 * @return mixed
	 * @throws \think\exception\DbException
	 */
    public function coordination()
	{
		if ($this->request->isAjax()) {
			$params = $this->request->param();
			$params['operation_type'] = 2;
			$approval = (new MyApprovalModel())->approvalLists($params);
			$this->success('success', '', $approval, 0);
		}

		return $this->fetch();
	}

	/**
	 * User: wufeng
	 * Date: 2020/04/06
	 *
	 * @return mixed
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function launch_coordination()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$params = input('post.');
			$where = $data = [];
			$approval = (new MyApprovalModel())->get($params['id']);
			$where['approver_id'] = get_current_id();
			$where['approval_id'] = $params['id'];
			$data['status'] = $params['status'];
			$data['approval_content'] = $params['approval_content'];
			$data['approval_time'] = date('Y-m-d H:i:s');
			Db::name('edu_my_approval_relation')->where($where)->update($data);

			$my_approval_count = Db::name('edu_my_approval_relation')->where(['approval_id' => $params['id']])->count();
			$my_approval_status_count = Db::name('edu_my_approval_relation')->where(['approval_id' => $params['id'], 'status' => 2])->count();
			if ($my_approval_count === $my_approval_status_count) {
				Db::name('edu_my_approval')->where(['id' => $params['id']])->update(['status' => 2]);
				CommonService::writeNotice($approval['user_id'], $approval['approval_name'], $approval['approval_name'].'协同'.'已被处理', 1, 2);
			}
			$this->success('操作成功', '', '', 1);
		}

		$approval = (new MyApprovalModel())->get(input('id'));
		$approval['user_name'] = (new UserModel())->get($approval['user_id'])['name'];
		$approval_lists = (new MyApprovalRelationModel())
			->where(['approval_id' => input('id')])
			->select()
			->toArray();
		foreach ($approval_lists as &$list) {
			$user = (new UserModel())->get($list['approver_id']);
			$list['name'] = $user['name'];
			if(1 === (int) $user['img']){
				$list['img'] = '/img.jpg';
			}else{
				$list['img'] = $user['img'];
			}
			if (1 === (int) $list['status']) {
				$list['status_text'] = '<span style="color:#c4f2f9;font-weight: bold;">待处理</span>';
			} elseif (2 === (int) $list['status']) {
				$list['status_text'] = '<span style="color:#00B83F;font-weight: bold;">已处理</span>';
			}
		}

		return $this->fetch('', [
			'approval' => $approval,
			'approval_lists' => $approval_lists,
		]);
	}
}
